package com.mebs.edi.scheduler.email;

import java.util.Properties;

import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Message.RecipientType;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import org.apache.log4j.Logger;

import com.mebs.edi.model.email.Email;

public class EmailSender {
	
	private static final Logger LOG = Logger.getLogger(EmailSender.class);
	
	private Properties smtpProperties;
	
	public EmailSender(String smtpHost, String smtpPort) {
		super();
		
		LOG.debug("instantiating EmailSender using host: " + smtpHost + "; and port: " + smtpPort);
		
		smtpProperties = new Properties();
		smtpProperties.put("mail.smtp.host", smtpHost);
		smtpProperties.put("mail.smtp.port", smtpPort);
	}
	
	public void sendEmail(Email email) throws MessagingException {
		LOG.debug("Sending email: " + email);
		
		Session session = Session.getDefaultInstance(smtpProperties, null);
		MimeMessage message = new MimeMessage(session);
		
		try {
			message.setFrom(new InternetAddress(email.getSender()));
			for (String recipient : email.getRecipients()) {
				InternetAddress recipientAddress = new InternetAddress(recipient);
				message.addRecipient(RecipientType.TO, recipientAddress);
			}
			message.setSubject(email.getSubject());
			message.setText(email.getText());
			
			Transport transport = session.getTransport("smtp");
			transport.connect();
			transport.sendMessage(message, message.getAllRecipients());
		    transport.close();
		    
		} catch (MessagingException e) {
			LOG.error("Error sending email", e);	
			throw e;
		}
		
		LOG.debug(email + " has been sent succesfully");
	}

	public String getSmtpHost() {
		return (String) smtpProperties.get("mail.smtp.host");
	}

	public void setSmtpHost(String smtpHost) {
		smtpProperties.put("mail.smtp.host", smtpHost);
		
	}

	public String getSmtpPort() {
		return (String) smtpProperties.get("mail.smtp.port");
	}

	public void setSmtpPort(String smtpPort) {
		smtpProperties.put("mail.smtp.port", smtpPort);
	}
}
